﻿using AntdUI;
using JinYuan.Helper;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Language;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmLogin : MultiLanguageForm
    {
        public FrmLogin()
        {
            InitializeComponent();
            InitializeLanguageSwitch();
            InitializeFormSettings();

            this.Load += FrmLogin_Load;
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            CommonMethods.GetSysConfig();
            if (CommonMethods.sysConfig != null)
            {
                if (CommonMethods.sysConfig.AutoLogin)
                {
                    btn_Login_Click(null, null);
                }
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Login_Click(object sender, EventArgs e)
        {
            //数据验证
            if (this.txt_LoginName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxOutWithAck(2, "请填写登录用户名".Translated(), "登录提示".Translated()).ShowDialog();
                this.txt_LoginName.Focus();
                return;
            }
            if (this.txt_LoginPwd.Text.Trim().Length == 0)
            {
                new FrmMsgBoxOutWithAck(2, "请填写登录密码".Translated(), "登录提示".Translated()).ShowDialog();
                this.txt_LoginPwd.Focus();
                return;
            }

            //封装对象
            SysAdmin sysAdminModel = new SysAdmin()
            {
                LoginName = this.txt_LoginName.Text.Trim(),
                LoginPwd = StringSecurityHelper.DESEncrypt(this.txt_LoginPwd.Text.Trim())
            };


            //调用查询方法

            SysAdmin sysAdmin = CommonMethods.db.Query<SysAdmin>(it => it.LoginName == sysAdminModel.LoginName && it.LoginPwd == sysAdminModel.LoginPwd);
            if (sysAdmin == null)
            {
                new FrmMsgBoxOutWithAck(3, "登录用户或密码错误".Translated(), "登录提示".Translated()).ShowDialog();
                return;
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                CommonMethods.LoginOut = false;
                //存储用户对象
                CommonMethods.currentAdmin = sysAdmin;
                CommonMethods.IsLoginOk = true;
            }

            //登陆后获取数据库表头
            List<string[]> SqlFieldsOut = CommonMethods.m_DBCtrl.SQLAllDataSearchToStrArrList(CommonMethods.dBSQL.GetSqlFields(CommonMethods.m_DBCtrl.machineOutSQLTable));
            CommonMethods.m_DBCtrl.HeaderTextOut = CommonMethods.m_DBCtrl.HeaderTextAssignment(SqlFieldsOut, 2);//本地数据文件表头

        }

        /// <summary>
        /// 回车按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Login_KeyDown(object sender, KeyEventArgs e)
        {
            //数据验证
            if (this.txt_LoginName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxOutWithAck(2, "请填写登录用户名".Translated(), "登录提示".Translated()).ShowDialog();
                this.txt_LoginName.Focus();
                return;
            }
            if (this.txt_LoginPwd.Text.Trim().Length == 0)
            {
                new FrmMsgBoxOutWithAck(2, "请填写登录密码".Translated(), "登录提示".Translated()).ShowDialog();
                this.txt_LoginPwd.Focus();
                return;
            }

            //封装对象
            SysAdmin sysAdmin = new SysAdmin()
            {
                LoginName = this.txt_LoginName.Text.Trim(),
                LoginPwd = StringSecurityHelper.DESEncrypt(this.txt_LoginPwd.Text.Trim())
            };

            //调用查询方法
            sysAdmin = CommonMethods.db.Query<SysAdmin>(it => it.LoginName == sysAdmin.LoginName && it.LoginPwd == sysAdmin.LoginPwd);
            if (sysAdmin == null)
            {
                new FrmMsgBoxOutWithAck(3, "登录用户或密码错误".Translated(), "登录提示".Translated()).ShowDialog();
                return;
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                CommonMethods.LoginOut = false;
                //存储用户对象
                CommonMethods.currentAdmin = sysAdmin;
                CommonMethods.IsLoginOk = true;
            }
        }

        private void txt_LoginName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btn_Login_Click(null, null);
            }
        }

        private void txt_LoginName_DoubleClick(object sender, EventArgs e)
        {
            StartKeyBoard();
        }


        #region 启动软键盘
        private void StartKeyBoard()
        {
            //打开软键盘
            try
            {
                if (!System.IO.File.Exists(Environment.SystemDirectory + "\\osk.exe"))
                {
                    MessageBox.Show("软件盘可执行文件不存在！");
                    return;
                }

                softKey = System.Diagnostics.Process.Start(Environment.SystemDirectory + "\\osk.exe");
                // 上面的语句在打开软键盘后，系统还没用立刻把软键盘的窗口创建出来了。所以下面的代码用循环来查询窗口是否创建，只有创建了窗口
                // FindWindow才能找到窗口句柄，才可以移动窗口的位置和设置窗口的大小。这里是关键。
                IntPtr intptr = IntPtr.Zero;
                while (IntPtr.Zero == intptr)
                {
                    System.Threading.Thread.Sleep(100);
                    intptr = FindWindow(null, "屏幕键盘");
                }


                // 获取屏幕尺寸
                int iActulaWidth = Screen.PrimaryScreen.Bounds.Width;
                int iActulaHeight = Screen.PrimaryScreen.Bounds.Height;


                // 设置软键盘的显示位置，底部居中
                int posX = (iActulaWidth - 1000) / 2;
                int posY = (iActulaHeight - 300);


                //设定键盘显示位置
                MoveWindow(intptr, posX, posY, 1000, 300, true);


                //设置软键盘到前端显示
                SetForegroundWindow(intptr);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        // 申明要使用的dll和api
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "MoveWindow")]
        public static extern bool MoveWindow(System.IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);


        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);


        private System.Diagnostics.Process softKey;

        #endregion

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Close();
        }

        #region 窗体拖动
        public static Point CPoint;

        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            CPoint = new Point(-e.X, -e.Y);
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point myPosittion = Control.MousePosition;//获取当前鼠标的屏幕坐标
                myPosittion.Offset(CPoint.X, CPoint.Y);//重载当前鼠标的位置
                this.DesktopLocation = myPosittion;//设置当前窗体在屏幕上的位置
            }
        }
        #endregion

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }

        private void InitializeFormSettings()
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint |
                         ControlStyles.DoubleBuffer |
                         ControlStyles.ResizeRedraw |
                         ControlStyles.Selectable |
                         ControlStyles.SupportsTransparentBackColor, true);
        }
        #endregion


        private void InitializeLanguageSwitch()
        {
            SwitchLanguage.Items.Clear();
            SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.中国国旗, "中文"));
            SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.美国国旗, "English"));
            SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.匈牙利国旗, "Hungary"));
            SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.马来西亚国旗, "Malaysia"));
        }

        /// <summary>
        /// 切换语言
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SwitchLanguage_SelectedValueChanged(object sender, ObjectNEventArgs e)
        {
            if (e.Value is SelectItem selectedItem)
            {
                string selectedLanguage = selectedItem.Text;
                string languageCode = selectedLanguage switch
                {
                    "中文" => "zh",
                    "English" => "en",
                    "Hungary" => "hu",
                    "Malaysia" => "ms",
                    _ => "zh"
                };
                LanguageManager.ChangeLanguage(languageCode);
            }
        }

    }
}
